from PyQt4.QtCore import Qt
from PyQt4.QtCore import QRectF
from PyQt4.QtGui import QGraphicsItem
from PyQt4.QtGui import QRadialGradient
from PyQt4.QtGui import QGraphicsTextItem
from PyQt4.QtGui import QStyle
from PyQt4.QtGui import QColor
from PyQt4.QtGui import QPen
from PyQt4.QtGui import QWidget
from PyQt4.QtGui import QGraphicsView
from PyQt4.QtGui import QGraphicsScene
from PyQt4.QtGui import QVBoxLayout

from ninja_ide.gui.main_panel import itab_item
from ninja_ide.tools import introspection
from ninja_ide.core import file_manager


class ClassDiagram(QWidget, itab_item.ITabItem):

    def __init__(self, actions, parent=None):
        QWidget.__init__(self, parent)
        itab_item.ITabItem.__init__(self)
        self.actions = actions
        self.graphicView = QGraphicsView(self)
        self.scene = QGraphicsScene()
        self.graphicView.setScene(self.scene)
        self.graphicView\
            .setViewportUpdateMode(QGraphicsView.BoundingRectViewportUpdate)

        vLayout = QVBoxLayout(self)
        self.setLayout(vLayout)
        vLayout.addWidget(self.graphicView)
        self.scene.setItemIndexMethod(QGraphicsScene.NoIndex)
        self.scene.setSceneRect(-200, -200, 400, 400)
        self.graphicView.setMinimumSize(400, 400)
        actualProject = self.actions.ide.explorer.get_actual_project()
        arrClasses = self.actions._locator\
                .get_classes_from_project(actualProject)

        #FIXME:dirty need to fix
        self.mX = -400
        self.mY = -320
        self.hightestY = self.mY
        filesList = []
        for elem in arrClasses:
            #loking for paths
            filesList.append(elem[2])
        for path in set(filesList):
            self.createClass(path)

    def createClass(self, path):
        content = file_manager.read_file_content(path)
        items = introspection.obtain_symbols(content)
        mYPadding = 10
        mXPadding = 10
        for classname, classdetail in items["classes"].iteritems():
            cl = ClassModel(self.graphicView, self.scene)
            cl.setClassName(classname)
            self.fillClases(cl, classdetail[1])
            self.scene.addItem(cl)
            cl.setPos(self.mX, self.mY)
            self.mX += cl._getWidth() + mXPadding
            if self.hightestY < self.mY + cl.getHeight():
                self.hightestY = self.mY + cl.getHeight()
            if self.mX > 2000:
                self.mX = -400
                self.mY += self.hightestY + mYPadding

    def fillClases(self, classComponent, classContent):
        funct = classContent['functions']
        classComponent.setFunctionsList(funct)
        attr = classContent['attributes']
        classComponent.setAttributesList(attr)

    def scaleView(self, scaleFactor):
            factor = self.graphicView.transform()\
                .scale(scaleFactor, scaleFactor)\
                .mapRect(QRectF(0, 0, 1, 1)).width()
            self.graphicView.scale(scaleFactor, scaleFactor)

    def keyPressEvent(self, event):

        taskList = {
                  Qt.Key_Plus: lambda: self.scaleView(1.2),
                  Qt.Key_Minus: lambda: self.scaleView(1 / 1.2)
        }
        if(event.key() in taskList):
            taskList[event.key()]()
        else:
            QWidget.keyPressEvent(self, event)


class ClassModel(QGraphicsItem):

    def __init__(self, parent=None, graphicView=None, graphicScene=None):
        QGraphicsItem.__init__(self)
        self.setDefaultData()
        self.className = QGraphicsTextItem(self)
        self.functionsItem = FunctionsContainerModel(self)
        self.className.setPlainText(self.defaultClassName)
        self.setFlag(self.ItemIsMovable)
        self.setFlag(self.ItemSendsGeometryChanges)
        self.functionsItem.setPos(0, self.__getTitleHeight())
        self.attributesItem = FunctionsContainerModel(self)
        self.attributesItem.setPos(0, self.functionsItem.getHeight())

    def setDefaultData(self):
        self.maxWidth = 100
        self.defaultClassNameHeight = 30
        self.defaultClassName = "No name"

    def setFunctionsList(self, functionsList):
        self.functionsItem.setFunctionsList(functionsList, "*", "()")
        self.updatePositions()

    def setAttributesList(self, attributesList):
        self.attributesItem.setFunctionsList(attributesList)
        self.updatePositions()

    def setClassName(self, className):
        self.className.setPlainText(className)

    def _getWidth(self):
        self.__calcMaxWidth()
        return self.maxWidth

    def __getTitleHeight(self):
        titleHeight = self.defaultClassNameHeight
        if titleHeight == self.className.document().size().height():
            titleHeight = self.className.document().size().height()
        return titleHeight

    def getHeight(self):
        summary = self.defaultClassNameHeight
        summary += self.functionsItem.getHeight()
        summary += self.attributesItem.getHeight()
        return summary

    def __calcMaxWidth(self):
        if self.maxWidth < self.className.document().size().width():
            self.maxWidth = self.className.document().size().width()
        if hasattr(self, "functionsItem"):
            if self.maxWidth < self.functionsItem.getWidth():
                self.maxWidth = self.functionsItem.getWidth()
        if hasattr(self, "attributesItem"):
            if self.maxWidth < self.attributesItem.getWidth():
                self.maxWidth = self.attributesItem.getWidth()

    def setBgColor(self, qColor):
        self.backgroundColor = qColor

    def setMethodList(self, itemList):
        self.methodList = itemList

    def updatePositions(self):
        self.functionsItem.setPos(0, self.__getTitleHeight())
        self.attributesItem.setPos(0, self.functionsItem.y() \
                             + self.functionsItem.getHeight())

    def paint(self, painter, option, widget):
        gradient = QRadialGradient(-3, -3, 10)
        if option.state & QStyle.State_Sunken:
            gradient.setCenter(3, 3)
            gradient.setFocalPoint(3, 3)
            gradient.setColorAt(0, QColor(Qt.yellow).light(120))
        else:
            gradient.setColorAt(0, QColor(Qt.yellow).light(120))
        painter.setBrush(gradient)
        painter.setPen(QPen(Qt.black, 0))
        painter.drawRoundedRect(self.boundingRect(), 3, 3)

    def boundingRect(self):
        return QRectF(0, 0, self._getWidth(), self.getHeight())

    def addEdge(self, edge):
        self.myEdge = edge
        edge.adjust()


class FunctionsContainerModel(QGraphicsItem):

    def __init__(self, parent=None):
        QGraphicsItem.__init__(self, parent)
        self.parent = parent
        self.maxWidth = self.parent._getWidth()
        self.maxHeight = 0

    def paint(self, painter, option, widget):
        painter.drawLine(self.boundingRect().topLeft(),\
                        self.boundingRect().topRight())

    def setFunctionsList(self, functionsList, prefix="", sufix=""):
        self.funtionsList = functionsList
        self.funtionsListItems = []
        self.maxHeight = 0
        tempHeight = 0
        for element in functionsList:
            tempElement = QGraphicsTextItem(self)
            tempElement.setPlainText(prefix + element + sufix)
            tempElement.setPos(0, tempHeight)
            tempHeight += tempElement.document().size().height()
            if self.maxWidth < tempElement.document().size().width():
                self.maxWidth = tempElement.document().size().width()
            self.funtionsListItems.append(tempElement)
        self.maxHeight = tempHeight

    def getHeight(self):
        return self.maxHeight

    def getWidth(self):
        if self.parent.maxWidth < self.maxWidth:
            return self.maxWidth
        else:
            return self.parent.maxWidth

    def boundingRect(self):
        return QRectF(0, 0, self.getWidth(), self.getHeight())


class Arrow(QGraphicsItem):

    def __init__(self, classSource, classDest, parent=None):
        self.arrowSize = 10
        self.source = classSource
        self.dest = classDest
        self.source.addEdge(self)

    def adjust(self):
        line = QLineF(self.mapToItem(self.source), 0, 0)
